package pl.edu.agh.iosr.gamblingzone.userpanel.action;

import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.ejb.Remove;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;

import pl.edu.agh.iosr.gamblingzone.dao.MoneyVoucherDAO;
import pl.edu.agh.iosr.gamblingzone.dao.ejb.MoneyVoucherDAOBean;
import pl.edu.agh.iosr.gamblingzone.model.MoneyVoucher;
import pl.edu.agh.iosr.gamblingzone.model.User;
import pl.edu.agh.iosr.gamblingzone.utils.DAOFactory;

@Stateless
@Name("voucherValidator")
public class MoneyVoucherValidatorAction implements MoneyVoucherValidator {

	@In
	private User user;

	@PersistenceContext
	private EntityManager em;

	@In(required = true)
	DAOFactory dao;

	@Logger
	Log log;

	@In
	private FacesMessages facesMessages;

	private String voucherHashCode;
	private Collection<MoneyVoucher> vouchers = new LinkedList<MoneyVoucher>();
	private List<MoneyVoucher> allVouchers;

	public void submit() {
		if ((voucherHashCode == null) || (voucherHashCode.length() == 0)) {
			facesMessages.add("Above field needs to be filled");
			return;
		}

		user = em.merge(user);

		MoneyVoucherDAO voucherDAO = dao.getVoucherDAO();
		vouchers.clear();

		int pages = voucherDAO.getPageCount();

		for (int i = 0; i < pages; i++) {
			vouchers.addAll(voucherDAO.findAllActive(user, i));
		}
		
		//TODO move method to dao; findAllActive()
		allVouchers = voucherDAO.findAll();
		for (MoneyVoucher voucher : allVouchers) {
			if(voucher.isActive()) {
				vouchers.add(voucher);
			}
		}

		Date today = new Date();
		boolean success = false;

		for (MoneyVoucher voucher : vouchers) {
			if (voucherHashCode.equals(voucher.getVoucherHash())
					&& (today.before(voucher.getExpirationDate()))) {
				voucher.setActive(false);
				Long balance = user.getBalance();
				balance += voucher.getValue();
				user.setBalance(balance);
				success = true;
			}
		}
		if (success) {
			facesMessages.add("Your account was updated");
		} else {
			facesMessages.add("Voucher's hash code invalid");
		}
	}

	public String getVoucherHashCode() {
		return voucherHashCode;
	}

	public void setVoucherHashCode(String voucherHashCode) {
		this.voucherHashCode = voucherHashCode;
	}

	@Remove
	public void destroy() {
	}
}
